package com.afishing.servlet;

import com.afishing.dao.UserDao;
import com.afishing.dao.impl.UserDaoImpl;
import com.afishing.entity.User;
import com.afishing.utils.JDBCUtil;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet(name = "RegisterServlet", value = "/register-servlet")
public class RegisterServlet extends HttpServlet {

    UserDao userDao = new UserDaoImpl();


    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        ServletContext application=this.getServletContext();

        //设置请求和响应的编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取请求参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 注册后将用户信息存入session
        User user = new User(null, username, password);
        HttpSession session = request.getSession();
//        session.setAttribute("username", username);
//        System.out.println(session.getAttribute("username"));
//        session.setAttribute("password", password);
        session.setAttribute("user", user);
        //将用户信息存入数据库
//        int update = JDBCUtil.update("insert into user(id,username,password) values(null,?,?)", username, password);
        Boolean update = userDao.RegisterUser(user);

        //如果注册的账号数据库已经存在，则返回注册页面
        if (update) {
            ArrayList users = (ArrayList) application.getAttribute("users");
            if (users == null) {
                users = new ArrayList();
                application.setAttribute("users", users);
            }
            ArrayList msgs = (ArrayList) application.getAttribute("msgs");
            if (msgs == null) {
                msgs = new ArrayList();
                application.setAttribute("msgs", msgs);
            }
            users.add(user);
            msgs.add(user.getUsername() + "进入了聊天室");
            response.sendRedirect("navbar.html");
        } else {
            response.sendRedirect("register.jsp");
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.doGet(req, resp);
    }
}
